from flask import Flask, request, jsonify, render_template
import math

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/calculate', methods=['POST'])
def calculate():
    try:
        data = request.get_json()
        operation = data.get('operation', 'power')
        
        if operation == 'power':
            # 次方运算
            base = float(data['base'])
            exponent = float(data['exponent'])
            result = math.pow(base, exponent)
            expression = f"{base}^{exponent}"
            
        elif operation in ['add', 'subtract', 'multiply', 'divide']:
            # 四则运算
            num1 = float(data['num1'])
            num2 = float(data['num2'])
            
            if operation == 'add':
                result = num1 + num2
                expression = f"{num1} + {num2}"
            elif operation == 'subtract':
                result = num1 - num2
                expression = f"{num1} - {num2}"
            elif operation == 'multiply':
                result = num1 * num2
                expression = f"{num1} × {num2}"
            elif operation == 'divide':
                if num2 == 0:
                    return jsonify({
                        'success': False,
                        'error': '除数不能为零'
                    })
                result = num1 / num2
                expression = f"{num1} ÷ {num2}"
        
        return jsonify({
            'success': True,
            'result': result,
            'expression': expression
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        })

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)
